<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>form表单提交</title>
</head>
<body>
    <form id="myForm">
        用户名：<input type="text" id="userName" name="userName"/><br>
        密码：<input type="password" id="password" name="password"><br/>
        手机号码：<input type="text" id="phoneNumber" name="phoneNumber"/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>
<script>

 var registerForm = document.getElementById("myForm");
    registerForm.onsubmit = function(){
        var errorMsg = validataFunc();
        if(errorMsg){
            alert(errorMsg);
            return false;
        }
    }

    //策略
    var strategies = {
        isNotEmpty:function(value,errorMsg){
            if(value === ""){
                return errorMsg;
            }
        },
        minLength:function(value,length,errorMsg){ //限制最小长度
            if(value.length < length){
                return errorMsg;
            }
        },
        isMobile:function(value,errorMsg){
            if ( !/(^1[ 3| 5| 8][ 0- 9]{ 9}$)/. test( value ) ){ return errorMsg; }
        }
    };

    //验证函数
    var validataFunc = function(){
        var validator = new Validatior();

        //添加校验规则
        validator.add(registerForm.userName,"isNotEmpty","用户名不能为空");
        validator.add(registerForm.password,"minLength:6","密码长度不能少于6位");
        validator.add(registerForm.phoneNumber,"isMobile","手机号码格式不正确");

        var errorMsg = validator.start();
        return errorMsg;
    }

    var Validatior = function(){
        this.cache = [];
    }

    Validatior.prototype.add = function(dom,rule,errorMsg){
        var ary = rule.split(":");
        this.cache.push(function(){
            var strategy = ary.shift();
            ary.unshift(dom.value);
            ary.push(errorMsg);
            return strategies[strategy].apply(dom,ary);
        });
    }
    Validatior.prototype.start = function(){
        for(var  i = 0,validataFunc;validataFunc=this.cache[i++];){
            var msg = validataFunc();
            if(msg){
                return msg;
            }
        }
    }
</script>